import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createContainer } from 'utils/hoc'
import ContentBox from 'components/contentBox'
import CustomTable from 'components/common/table'
import { Form, message, Button, Modal, Input, Select } from 'antd'
import PropTypes from 'prop-types'
import Style from './banner.css'

const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 16 }
}
const { Option } = Select
const { TextArea } = Input
const pushType = {
  1: '自动推送',
  2: '人工推送'
}

const messageType = {
  'REGISTER_CONSUMER': '注册会员',
  'INTEGRAL_REMIND': '积分到期提醒',
  'INTEGRAL_CHANGE': '积分变动通知',
  'CONSUMER_CHANGE': '会员身份变动',
  'DELIVERY_REMIND': '流程反馈-发货提醒',
  'REFUND_SUCCESS': '流程反馈-退款成功',
  'INVITE_FRIENDS': '邀请好友',
  'BIRTHDAY_WISHES': '生日祝福',
  'PARTICULAR_ACTIVITY': '特定营销活动'
}
class IndexForm extends Component {
  static propTypes = {
    form: PropTypes.object,
    getPushList: PropTypes.func,
    pushData: PropTypes.object
  }
  constructor (props) {
    super(props)
    this.state = {
      pageNo: 1,
      pageSize: 20,
      params: {},
      editParams: {}
    }
    this.search = this.search.bind(this)
    this.reset = this.reset.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
    this.onShowSizeChange = this.onShowSizeChange.bind(this)
    this.handleAdd = this.handleAdd.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    this.handleOk = this.handleOk.bind(this)
  }

  getTableCols () {
    return [
      {
        title: '编号',
        dataIndex: 'code',
        key: 'code',
        width: 100
      },
      {
        title: '推送类型',
        dataIndex: 'pushType',
        key: 'pushType',
        width: 100,
        render: text => pushType[text]
      },
      {
        title: '消息类型',
        dataIndex: 'msgType',
        key: 'msgType',
        width: 100,
        render: text => messageType[text]
      },
      {
        title: '推送方式',
        dataIndex: 'pushTitle',
        key: 'pushTitle',
        width: 100
      },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        render: (text, record) => {
          return <a className={Style['a-btn']} onClick={() => this.handleEdit(record)}>编辑</a>
        },
        width: 100
      }
    ]
  }

  reset () {
    this.setState({
      pageNo: 1,
      pageSize: 20,
      params: {}
    })
    this.props.getPushList({
      pageNo: 1,
      pageSize: 20,
      pushType: 1
    })
  }

  search (values = {}) {
    const { pageSize, pageNo } = this.state
    values.pageNo = pageNo
    values.pageSize = pageSize
    values.pushType = 1
    this.setState({
      params: values
    })
    this.props.getPushList(values)
  }

  handleAdd () {
    this.setState({
      showModal: true,
      title: '新增自动推送',
      formStatus: 'add'
    })
  }

  handleOk () {
    const { formStatus, editParams } = this.state
    this.props.form.validateFieldsAndScroll((err, values) => {
      values.pushType = 1
      delete values.rules
      if (!err) {
        if (formStatus === 'edit') {
          values.id = editParams.id
          this.props.editPush(values)
        } else {
          this.props.createPush(values)
        }
      }
    })
  }

  handleCancel () {
    this.setState({
      showModal: false
    })
  }

  handleEdit (editParams) {
    this.setState({
      showModal: true,
      formStatus: 'edit',
      title: '编辑banner',
      image: editParams.image,
      editParams,
      width: editParams.width,
      height: editParams.height
    })
  }

  onPageChange (pageNo, pageSize) {
    const { params } = this.state
    params.pageNo = pageNo
    params.pageSize = pageSize
    this.setState({
      pageNo
    })
    params.pushType = 1
    this.props.getPushList(params)
  }

  onShowSizeChange (current, pageSize) {
    this.setState({
      pageSize
    })
    const { params } = this.state
    params.pageNo = current
    params.pageSize = pageSize
    params.pushType = 1
    this.props.getPushList(params)
  }

  componentDidMount () {
    const { pageSize, pageNo } = this.state
    this.props.getPushList({
      pageSize,
      pageNo,
      pushType: 1
    })
  }

  componentWillReceiveProps (nextProps) {
    if (!this.props.editPushRequest && nextProps.editPushRequest) {
      this.setState({
        showModal: false
      })
      message.success('编辑成功')
      this.search()
    }

    if (!this.props.createPushRequest && nextProps.createPushRequest) {
      this.setState({
        showModal: false
      })
      message.success('创建成功')
      this.search()
    }
  }

  render () {
    const { getFieldDecorator } = this.props.form

    const { pageNo, pageSize, showModal, title, editParams } = this.state
    const { pushData } = this.props
    const pagination = {
      showSizeChanger: true,
      current: pageNo,
      total: pushData && pushData.total,
      onChange: this.onPageChange,
      pageSize,
      onShowSizeChange: this.onShowSizeChange
    }
    return (
      <>
        <ContentBox>
          <div className={Style['scenes-RecycleForm']}>
            <Button type='primary' onClick={this.handleAdd}>新建自动推送</Button>
            <CustomTable
              loading={!pushData} columns={this.getTableCols()}
              dataSource={(pushData && pushData.list) || []}
              pagination={pagination} />
            <Modal
              title={title}
              visible={showModal}
              width={800}
              onOk={this.handleOk}
              destroyOnClose
              onCancel={this.handleCancel}
            >
              <Form {...formItemLayout}>
                <Form.Item label='推送标题'>
                  {getFieldDecorator('pushTitle', {
                    rules: [{ required: true, message: '请输入序号' }],
                    initialValue: editParams.pushTitle
                  })(
                    <Input placeholder='请输入' />
                  )}
                </Form.Item>
                <Form.Item label='消息类型'>
                  {getFieldDecorator('msgType', {
                    rules: [{ required: true, message: '请输选择消息类型' }],
                    initialValue: editParams.msgType
                  })(
                    <Select placeholder='请输入'>
                      <Option value='REGISTER_CONSUMER'>注册会员</Option>
                      <Option value='INTEGRAL_REMIND'>积分到期提醒</Option>
                      <Option value='INTEGRAL_CHANGE'>积分变动通知</Option>
                      <Option value='CONSUMER_CHANGE'>会员身份变动</Option>
                      <Option value='DELIVERY_REMIND'>流程反馈-发货提醒</Option>
                      <Option value='REFUND_SUCCESS'>流程反馈-退款成功</Option>
                      <Option value='INVITE_FRIENDS'>邀请好友</Option>
                      <Option value='BIRTHDAY_WISHES'>生日祝福</Option>
                      <Option value='PARTICULAR_ACTIVITY'>特定营销活动</Option>
                    </Select>
                  )}
                </Form.Item>
                <Form.Item label='内容模板'>
                  {getFieldDecorator('pushContent', {
                    rules: [{ required: true, message: '请输入内容模板' }],
                    initialValue: editParams.pushContent
                  })(
                    <TextArea placeholder='请输入' />
                  )}
                </Form.Item>
                <Form.Item label='替换规则'>
                  {getFieldDecorator('rules')(
                    <>
                      <div>用户名：$UserName$ 订单号：$OrderId$ 订单金额：$Total$</div>
                      <div>配送方式：$Shipping_Type$ 收货人姓名：$Shipping_Name$ 收货人地址：$Shipping_Addr$</div>
                      <div>收货人邮编：$Shipping_Zip$ 收货人电话：$Shipping_Phone$ 收货人手机：$Shipping_Cell$</div>
                      <div>收货人Email：$Shipping_Email$ 备注：$Memo$</div>
                      <div>物流单号：$Shipping_Logistics_No$</div>
                    </>
                  )}
                </Form.Item>
              </Form>
            </Modal>
          </div>
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  pushData: state.operation.pushData,
  createPushRequest: state.operation.createPushRequest,
  editPushRequest: state.operation.editPushRequest
})
const mapDispatch = dispatch => ({
  getPushList: dispatch.operation.getPushList,
  createPush: dispatch.operation.createPush,
  editPush: dispatch.operation.editPush
})

const Index = Form.create()(IndexForm)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(Index)
)
